//
//  TSNetworkManager.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/10/21.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import Moya

private func endpointMapping<Target: TargetType>(target: Target) -> Endpoint {
    
//    let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
//    return defaultEndpoint.adding(newHttpHeaderFields: ["APP_NAME": "MY_AWESOME_APP"])

    print("请求连接：\(target.baseURL)\(target.path)--方法：\(target.method)")
    
    return MoyaProvider.defaultEndpointMapping(for: target)
}

let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider.RequestResultClosure) -> Void in

    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 10
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

public final class NetworkActivityPlugin: PluginType {

    public typealias NetworkActivityClosure = (_ change: NetworkActivityChangeType) -> ()
    
    let networkActivityClosure: NetworkActivityClosure

    public init(networkActivityClosure: @escaping NetworkActivityClosure) {
        self.networkActivityClosure = networkActivityClosure
    }

    // MARK: Plugin

    /// Called by the provider as soon as the request is about to start
    public func willSend(request: RequestType, target: TargetType) {
        networkActivityClosure(.began)
    }

    /// Called by the provider as soon as a response arrives
    public func didReceive(data: Data?, statusCode: Int?, response: URLResponse?, error: Error?, target: TargetType) {
        networkActivityClosure(.ended)
    }
}

let networkPlugin = TSNetworkActivityPlugin { (state,target) in
    
    let api = target as! TMSNetworkTools
        
        if state == .began {
            
            print("我可以在这里写加载提示")
            
//            if api.show {
//                print("我可以在这里写加载提示")
//                if !api.touch {
//                    print("我可以在这里写禁止用户操作，等待请求结束")
//                }
//    //            SVPHUDTool.showHUD(api.touch,api.title)
//            }
            
        } else {
            //        SwiftSpinner.show("request finish...")
            //        SwiftSpinner.hide()
            
//            if api.show {
//    //           SVPHUDTool.dismiss()
//            }
            
            print("我结束请求")
            
        }
}

class TSNetworkManager: NSObject {

    class func request<T:TargetType>(_ target:T, showHUD:Bool,
                                success successCallback: @escaping(Any) -> Void,
                                failure failureCallback: @escaping(Any) -> Void
                                ) {
        
        let provider = MoyaProvider<T>(endpointClosure: endpointMapping, requestClosure:timeoutClosure)
        
        // 取消所有请求
//        provider.manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
//            dataTasks.forEach{$0.cancel()}
//            uploadTasks.forEach{$0.cancel()}
//            downloadTasks.forEach{$0.cancel()}
//        }

        provider.request(target) { (result) in
            switch result {

            case  let .success(response):
                do {
                    
                    let data = try response.mapJSON()
                    let statusCode = response.statusCode
                    
//                    print(data)
                    
                    if statusCode == 200 {
                        
                        let responseDic = data as? NSDictionary
                        if responseDic?.allKeys.count ?? 0 > 0 {
                            let code = "\(responseDic?.object(forKey: "code") ?? "-9999")"
                            if code == "1" {
                                successCallback(responseDic?["data"] as Any)
                            } else {
                                
                                if code == "0" {
                                    if target.path == "glist/xypklist" || target.path == "chongzhi/showlist" || target.path == "glist/shaixuan" || target.path == "item/index"
                                        {
                                        successCallback(responseDic?["data"] as Any)
                                        return
                                    }
                                }
                                
                                let msg = "\(responseDic?.object(forKey: "msg") ?? "")"
                                if showHUD {
                                    if msg.count > 0 {
                                        CBToast.showToastAction(message: msg as NSString)
                                    } else {
                                        CBToast.showToastAction(message: "请求超时，请稍后再试")
                                    }
                                }

                                failureCallback(NSNull.self)
                            }
                        } else {
                            if showHUD {
                                CBToast.showToastAction(message: "请求超时，请稍后再试")
                            }
                            failureCallback(NSNull.self)
                        }
                        
                    } else if (statusCode == 401) {
                        
                        NotificationCenter.default.post(name: .TSLogoutNotification, object: nil)
                        
                        CBToast.showToastAction(message: "用户信息异常，需要重新登录")
                        
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
                            TSLoginManager.shared.clearUserInfo()
//                            OYCountDownManager.sharedManager.removeAllSource()
//                            OYCountDownManager.sharedManager.invalidate()
                            UIApplication.shared.keyWindow?.rootViewController = TSLoginViewController()
                        }
                        
                    } else {
                        print("请求出错了")
                        if showHUD {
                            CBToast.showToastAction(message: "请求超时，请稍后再试")
                        }
                        failureCallback(NSNull.self)
                    }
                } catch {
                    // 捕获异常
                    print("异常了:\(error.localizedDescription)")
                    if showHUD {
                        CBToast.showToastAction(message: "请求超时，请稍后再试")
                    }
                    failureCallback(error)
                }
            case let .failure(error):
                TSLog("错误了:\(error.localizedDescription)")
                if showHUD {
                    CBToast.showToastAction(message: "请求超时，请稍后再试")
                }
                failureCallback(error)
                break
            }
        }
    }
}
